package com.lei.springbootpractice.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lei.springbootpractice.dao.OrdersDao;
import com.lei.springbootpractice.dao.ProductsDao;
import com.lei.springbootpractice.pojo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.HashSet; // 用于存储已评价的productId
import java.util.Set;     // 用于存储已评价的productId

@Service
public class OrdersService {
    @Autowired
    OrdersDao ordersDao;

    @Autowired
    ProductsService productsService;

    @Autowired
    CartService cartService;

    @Autowired
    ProductBunchService productBunchService;

    @Autowired
    AddressService addressService;

    @Autowired
    ProductsDao productsDao;

    @Autowired
    private ReviewService reviewService; // 确保 ReviewService 已经被注入

    Logger logger = LoggerFactory.getLogger(OrdersService.class);

    public List<OrdersPojo> getOrdersByUserId(String userId) {
        return ordersDao.selectList(new QueryWrapper<OrdersPojo>().eq("user_id", userId));
    }

    public List<OrdersPojo> getAllOrders(String status, String startDate, String endDate) {
        QueryWrapper<OrdersPojo> queryWrapper = new QueryWrapper<>();

        if (status != null && !status.isEmpty()) {
            queryWrapper.eq("status", status);
        }

        if (startDate != null && !startDate.isEmpty()) {
            queryWrapper.ge("date", startDate);
        }

        if (endDate != null && !endDate.isEmpty()) {
            queryWrapper.le("date", endDate);
        }

        queryWrapper.orderByDesc("date");
        return ordersDao.selectList(queryWrapper);
    }

    @Transactional
    public boolean createOrder(OrdersPojo order) {
        return ordersDao.insert(order) > 0;
    }

    @Transactional
    public boolean cancelOrder(String orderId) {
        return ordersDao.deleteById(orderId) > 0;
    }

    @Transactional
    public boolean payOrder(String orderId, String paymentType, String paymentAccount) {
        OrdersPojo order = ordersDao.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!"待支付".equals(order.getStatus())) {
            throw new RuntimeException("订单状态不允许支付");
        }
        if (paymentType == null || paymentType.isEmpty()) {
            throw new RuntimeException("请选择支付方式");
        }

        order.setStatus("已支付");
        order.setPaymentType(paymentType);
        order.setPaymentAccount(paymentAccount);
        order.setDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));

        return ordersDao.updateById(order) > 0;
    }

    @Transactional
    public boolean updateOrderStatus(String orderId, String status, String shippingCompany, String shippingNo) {
        OrdersPojo order = ordersDao.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (status == null || status.isEmpty()) {
            throw new RuntimeException("状态不能为空");
        }

        order.setStatus(status);
        if (shippingCompany != null) {
            order.setShippingCompany(shippingCompany);
        }
        if (shippingNo != null) {
            order.setShippingNo(shippingNo);
        }

        return ordersDao.updateById(order) > 0;
    }

    private double calculateTotalPrice(List<CartPojo> cartItems) {
        double total = 0.0;
        for (CartPojo item : cartItems) {
            for (ProductBunchPojo bunch : item.getProductBunches()) {
                ProductsPojo product = bunch.getProduct();
                if (product != null) {
                    total += product.getPrice() * bunch.getQuantity();
                }
            }
        }
        return total;
    }

    @Transactional(rollbackFor = Exception.class, isolation = Isolation.READ_COMMITTED)
    public boolean createOrderFromCart(String userId, String addressId) {
        logger.info("开始为用户 {} 创建订单，地址ID: {}", userId, addressId);

        try {
            // 1. 获取购物车信息
            List<CartPojo> cartItems = cartService.getCartByUserId(userId);
            if (cartItems.isEmpty()) {
                logger.warn("购物车为空，无法创建订单");
                throw new RuntimeException("购物车为空");
            }
            logger.debug("获取到 {} 个购物车项", cartItems.size());

            // 2. 验证地址
            validateAddress(userId, addressId);

            // 3. 创建订单
            OrdersPojo order = createOrder(userId, addressId, cartItems);
            logger.info("创建订单成功，订单ID: {}", order.getOrderId());

            // 4. 处理购物车商品
            for (CartPojo cart : cartItems) {
                for (ProductBunchPojo bunch : cart.getProductBunches()) {
                    logger.debug("处理商品ID: {}, 数量: {}", bunch.getProductId(), bunch.getQuantity());

                    // 原子性更新库存
                    int updated = productsDao.reduceInventory(bunch.getProductId(), bunch.getQuantity());
                    if (updated == 0) {
                        throw new RuntimeException("商品库存不足: " + bunch.getProductId());
                    }

                    // 更新商品状态
                    bunch.setOrderId(order.getOrderId());
                    bunch.setStatus("ORDERED");
                    bunch.setCartId(null);

                    if (!productBunchService.updateProductBunch(bunch)) {
                        throw new RuntimeException("更新商品关联关系失败");
                    }
                }
            }

            // 5. 保留购物车结构，只移除已下单商品
            logger.info("订单创建成功，订单总金额: {}", order.getTotalPrice());
            return true;

        } catch (Exception e) {
            logger.error("创建订单失败: {}", e.getMessage(), e);
            throw e; // 触发事务回滚
        }
    }

    private void validateAddress(String userId, String addressId) {
        if (addressId == null || addressId.isEmpty() || addressId.equals("undefined")) {
            throw new RuntimeException("请选择有效的收货地址");
        }

        AddressPojo address = addressService.getAddressById(addressId);
        if (address == null) {
            throw new RuntimeException("选择的收货地址不存在");
        }
        if (!address.getUserId().equals(userId)) {
            throw new RuntimeException("选择的收货地址不属于当前用户");
        }
    }

    private OrdersPojo createOrder(String userId, String addressId, List<CartPojo> cartItems) {
        OrdersPojo order = new OrdersPojo();
        order.setUserId(userId);
        order.setAddressId(addressId);
        order.setStatus("待支付");
        order.setPaymentType("未支付");
        order.setTotalPrice(calculateTotalPrice(cartItems));
        order.setDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        order.setShippingCompany("待指定");
        order.setShippingNo("待生成");
        order.setPaymentAccount("未设置");

        if (ordersDao.insert(order) <= 0) {
            throw new RuntimeException("订单创建失败");
        }
        return order;
    }

    private void updateProductInventory(ProductBunchPojo bunch) {
        ProductsPojo product = bunch.getProduct();
        int newRest = product.getRest() - bunch.getQuantity();
        if (newRest < 0) {
            throw new RuntimeException("商品库存不足: " + product.getProductName() +
                                   " (当前库存: " + product.getRest() + ", 需要: " + bunch.getQuantity() + ")");
        }
        product.setRest(newRest);
        if (!productsService.updateProduct(product)) {
            throw new RuntimeException("更新库存失败");
        }
    }

    public OrdersPojo getOrderDetail(String orderId) {
        OrdersPojo order = ordersDao.selectById(orderId);
        if (order != null) {
            populateOrderDetails(order); // 使用辅助方法填充详细信息
        }
        return order;
    }

    /**
     * 辅助方法，用于填充订单的详细信息，包括商品和评价状态。
     * 传入的 order 对象必须已经从数据库加载。
     */
    private void populateOrderDetails(OrdersPojo order) {
        // 1. 获取关联的商品捆绑信息
        List<ProductBunchPojo> productBunches = productBunchService.getByOrderId(order.getOrderId());

        // 2. 补充每个 productBunch 的具体商品信息
        for (ProductBunchPojo bunch : productBunches) {
            ProductsPojo product = productsService.getProductById(bunch.getProductId());
            if (product != null) {
                bunch.setProduct(product);
            }
            // 移除此处错误的 bunch.setReviewed(...) 调用
            // 我们将在 OrdersPojo 层面存储已评价的商品ID
        }
        order.setProductBunches(productBunches); // 设置到 OrdersPojo

        // 3. 获取该订单中所有已评价的商品ID
        Set<String> reviewedProductIds = new HashSet<>();
        // 调用 ReviewService 中新添加的方法来获取某个订单的所有评价
        List<ReviewPojo> reviewsForOrder = reviewService.getReviewsByOrderId(order.getOrderId());
        for (ReviewPojo review : reviewsForOrder) {
            reviewedProductIds.add(review.getProductId());
        }
        order.setReviewedProductIds(reviewedProductIds); // 设置到 OrdersPojo
    }


    @Transactional
    public boolean confirmReceipt(String orderId) {
        OrdersPojo order = ordersDao.selectById(orderId);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        if (!"已发货".equals(order.getStatus())) {
            throw new RuntimeException("只有已发货的订单才能确认收货");
        }

        order.setStatus("待评价");
        order.setDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        return ordersDao.updateById(order) > 0;
    }

    /**
     * 提交商品评价。
     *
     * @param orderId 订单ID
     * @param productId 商品ID
     * @param rating 评分
     * @param comment 评价内容
     * @return ReviewResult 包含成功状态、消息和订单是否已完成的标志
     */
    @Transactional
    public ReviewResult submitReview(String orderId, String productId, int rating, String comment) {
        OrdersPojo order = ordersDao.selectById(orderId);
        if (order == null) {
            return new ReviewResult(false, "订单不存在", false);
        }
        if (!"待评价".equals(order.getStatus())) {
            return new ReviewResult(false, "只有待评价的订单才能提交评价", false);
        }

        // 检查该用户是否已评价过此订单中的此商品
        if (reviewService.hasUserReviewedProductInOrder(order.getUserId(), productId, orderId)) {
            return new ReviewResult(false, "您已评价过此订单中的该商品，请勿重复提交", false);
        }

        // 1. 创建并保存评价记录
        ReviewPojo review = new ReviewPojo();
        review.setProductId(productId);
        review.setUserId(order.getUserId());
        review.setRate(rating);
        review.setComment(comment);
        review.setCreateTime(LocalDateTime.now());
        review.setOrderId(orderId); // 设置 order_id

        if (!reviewService.createReview(review)) {
            return new ReviewResult(false, "评价提交失败", false);
        }

        // 2. 检查订单下所有不重复的商品是否都已评价
        List<ProductBunchPojo> productBunches = productBunchService.getByOrderId(orderId);
        Set<String> distinctProductIdsInOrder = new HashSet<>();
        for (ProductBunchPojo bunch : productBunches) {
            // 确保 product 字段已加载，以便获取 productId
            ProductsPojo product = productsService.getProductById(bunch.getProductId());
            if (product != null) {
                bunch.setProduct(product); // 补充 product 信息，以防万一
                distinctProductIdsInOrder.add(bunch.getProductId());
            }
        }

        boolean allDistinctProductsReviewed = true;
        // 如果订单中没有商品，则不改变状态 (尽管这种情况不常见)
        if (distinctProductIdsInOrder.isEmpty()) {
             allDistinctProductsReviewed = false; // 或者根据业务逻辑处理，这里假设有商品才可能完成评价
        } else {
            for (String distinctProductId : distinctProductIdsInOrder) {
                if (!reviewService.hasUserReviewedProductInOrder(order.getUserId(), distinctProductId, orderId)) {
                    allDistinctProductsReviewed = false;
                    break;
                }
            }
        }

        // 3. 只有当所有不重复的商品都已评价时，才将订单状态更新为“已完成”
        if (allDistinctProductsReviewed) {
            order.setStatus("已完成");
            order.setDate(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
            boolean updated = ordersDao.updateById(order) > 0;
            return new ReviewResult(updated, updated ? "评价提交成功，订单已完成" : "评价提交成功，订单状态更新失败", true);
        } else {
            // 如果还有商品未评价，订单状态保持不变
            return new ReviewResult(true, "评价提交成功，仍有商品待评价", false);
        }
    }

    // 辅助类，用于返回评价结果和订单是否完成的状态
    public static class ReviewResult {
        private boolean success;
        private String message;
        private boolean orderCompleted;

        public ReviewResult(boolean success, String message, boolean orderCompleted) {
            this.success = success;
            this.message = message;
            this.orderCompleted = orderCompleted;
        }

        // Getters for success, message, orderCompleted
        public boolean isSuccess() {
            return success;
        }

        public String getMessage() {
            return message;
        }

        public boolean isOrderCompleted() {
            return orderCompleted;
        }
    }
}